import {PolicyDetailProvider} from '../../../providers/policy/policy-detail/policy-detail.provider';

import {Component, ViewChild} from '@angular/core';
import {IonicPage, NavController, NavParams, DateTime, ToastController} from 'ionic-angular';
import * as moment from 'moment';
import {LoanRecord, LoanRecordsGroup} from "../../../model/pages/policy/policy-detail/loan-record";
import {HttpErrorResponse} from "@angular/common/http";
import {LoadingService} from "../../../services/common/loading.service";

/**
 * Generated class for the LoanRecordPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-loan-record',
    templateUrl: 'loan-record.html',
    providers: [PolicyDetailProvider, LoadingService]
})
export class LoanRecordPage {
    /**
     * 显示的贷款记录数据
     * @type {any[]}
     */
    displayLoanRecordList: Array<LoanRecordsGroup> = [];

    /**
     * 原始的贷款记录数据
     * @type {any[]}
     */
    loanRecordList: Array<LoanRecordsGroup> = [];

    /**
     * 开始时间
     * @type {string}
     */
    startFilterDate = '';

    /**
     * 结束标签
     * @type {string}
     */
    endFilterDate = '';

    /**
     * 是否在加载数据
     * @type {boolean}
     */
    isLoaded: boolean = false;

    /**
     * 获取数据订阅
     */
    getDataSubscription: any;

    /**
     * 贷款费率
     */
    currentLoanRate: number;

    constructor(
        public navCtrl: NavController,
        public navParams: NavParams,
        private policyDetailProvider: PolicyDetailProvider,
        private toastController: ToastController,
        private loadingService: LoadingService) {
    }

    ionViewDidLoad() {

        // 获取id
        let id = this.navParams.get('id');

        this.currentLoanRate = this.navParams.get('currentLoanRate');

        // 获取数据
        if (id != null) {
            // 显示loading动画
            this.loadingService.showLoading();
            // 请求数据
            this.getDataSubscription = this.policyDetailProvider.getPolicyLoanList(id).subscribe(data => {
                // 排序
                // data.forEach(data => {
                //     data.loanRecords = data.loanRecords.sort((a: LoanRecord, b: LoanRecord) => {
                //         if (a.loanDate > b.loanDate) {
                //             return -1;
                //         }
                //         if (a.loanDate < b.loanDate) {
                //             return 1;
                //         }
                //         return 0;
                //     })
                // });

                this.loanRecordList = data;
                this.displayLoanRecordList = data;

                // 加载数据结束
                this.isLoaded = true;

                // 关闭loading动画
                this.loadingService.dismissLoading();
            }, (error: HttpErrorResponse) => {
                // 加载数据结束
                this.isLoaded = true;
                // 关闭loading动画
                this.loadingService.dismissLoading();
            })
        }
    }

    ionViewWillLeave() {
        // 取消订阅数据
        if (this.getDataSubscription) {
            this.getDataSubscription.unsubscribe();
        }
    }

    /**
     * 返回上一级
     */
    goBack() {
        this.navCtrl.pop();
    }

    /**
     * 筛选数据
     */
    filter() {

        // 校验时间范围是否正确
        if (this.endFilterDate === '' && this.startFilterDate === '') {
            let toast = this.toastController.create({
                message: '开始时间和结束时间不能同时为空',
                duration: 2000,
                position: 'middle'
            });
            toast.present();
            // this.cleanFilterDate();
            return;
        }


        if (this.endFilterDate != '' && this.startFilterDate != '' && this.endFilterDate < this.startFilterDate) {
            let toast = this.toastController.create({
                message: '结束时间不能早于开始时间，请重新选择',
                duration: 2000,
                position: 'middle'
            });
            toast.present();
            // this.cleanFilterDate();
            return;
        }
        //  将显示数据还原成原始数据
        this.displayLoanRecordList = JSON.parse(JSON.stringify(this.loanRecordList));

        // 开始筛选
        this.displayLoanRecordList = this.displayLoanRecordList.filter(data => {
            data.loanRecords = data.loanRecords.filter(record => {
                if (this.endFilterDate != '' && this.startFilterDate != '') {
                    return this.startFilterDate <= moment(record.loanDate * 1000).format('YYYY-MM') && this.endFilterDate >= moment(record.loanDate * 1000).format('YYYY-MM');
                }
                if (this.endFilterDate == '') {
                    return this.startFilterDate <= moment(record.loanDate * 1000).format('YYYY-MM');
                }
                if (this.startFilterDate == '') {
                    return this.endFilterDate >= moment(record.loanDate * 1000).format('YYYY-MM');
                }
            });


            return data.loanRecords.length != 0;
        });
    }


}
